package com.kcsj.controller.authority;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kcsj.domain.user.*;
import com.kcsj.service.user.*;
import com.kcsj.util.JSONUtil;
import com.kcsj.util.JWTResult;
import com.kcsj.util.MessageHelper;
import com.kcsj.util.TokenHelper;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
@Slf4j
@WebServlet("/login")
public class LoginController extends HttpServlet {
    /**
     * GET, http://localhost:8080/actor.ctl?id=1, 查询id=1的学院
     * GET, http://localhost:8080/actor.ctl, 查询所有的学院
     * 把一个或所有对象响应到前端
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //将request body转换为JSON字串
        String json = JSONUtil.getJSON(request);
        try {
            //将JSON字串解析为User对象
            User userToLogin = JSON.parseObject(json,User.class);
            //使用用户名查询用户
            User user = UserService.getInstance().login(userToLogin.getUsername());
            //判断用户是否存在
            if(user==null){
                JSONObject message = MessageHelper.accountNotExist();
                response.getWriter().println(message);
                //判断密码是否正确
            }else if(!user.getPassword().equals(userToLogin.getPassword())){
                JSONObject message = MessageHelper.passwordError();
                response.getWriter().println(message);
                //判断账号是否可用
            }else if(!user.getActivationStatus()){
                JSONObject message = MessageHelper.accountUnable();
                response.getWriter().println(message);
            }else {
                //生成登入日志
                this.addLoginLog(request,user);
                //拿到当前账号的详细信息
                User activeUser = this.getActiveUser(user.getId());
                String activeUser_json = JSON.toJSONString(activeUser);
                //用username生成token
                JWTResult jwtResult = new JWTResult(activeUser.getId(), activeUser.getUsername(), activeUser.getRole().getName());
                String token = TokenHelper.getToken(jwtResult);
                String flushToken = TokenHelper.getFlushToken(jwtResult);
                //登入成功
                JSONObject message = MessageHelper.loginSuccess();
                message.put("data",activeUser_json);
                //添加响应信息
                response.addHeader("token",token);
                response.addHeader("flushToken",flushToken);
                response.getWriter().print(message);
            }
        }catch (SQLException e){
            e.printStackTrace();
            JSONObject message = MessageHelper.dateBaseError();
            response.getWriter().print(message);
        }catch (Exception e) {
            e.printStackTrace();
            JSONObject message = MessageHelper.netWordError();
            response.getWriter().println(message);
        }
    }
    //生成登入日志
    private void addLoginLog(HttpServletRequest request,User user) throws SQLException {
        //浏览器基本信息
        String header = request.getHeader("user-agent");
        //转成UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        //获取浏览器信息
        Browser browser = userAgent.getBrowser();
        //浏览器名称
        String visitBrowser = browser.getName();
        //客户端系统名称
        String clientSystem = System.getProperty("os.name");
        //HTTP协议版本
        String HTTPProtocol = request.getProtocol();
        //WEB服务器的IP地址
        String ip = request.getLocalAddr();
        String loginLocation = getAddress(ip);
        LoginLog loginLog = new LoginLog(user, ip, loginLocation, visitBrowser, clientSystem, HTTPProtocol);
        LoginLogService.getInstance().add(loginLog);
    }
    //获取登入地址
    public static String getAddress(String ip) {
        String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
        String str = HttpUtil.get(url);
        if(!StrUtil.hasBlank(str)){
            String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1);
            JSONObject jsonObject = JSONObject.parseObject(substring);
            String province = jsonObject.getString("province");
            String city = jsonObject.getString("city");
            return province + " " + city;
        }
        return null;
    }
    //获取登入用户的详细信息
    private User getActiveUser(Integer id) throws SQLException {
        User login_user = UserService.getInstance().find(id);
        Collection<Resource> resources = RoleAssResourceService.getInstance().
                findRoleMenu(login_user.getRole().getId());
        login_user.setResources(resources);
        String type = login_user.getType();
        if(type.equals("员工")){
            Employee info = EmployeeService.getInstance().findInfo(login_user.getId());
            login_user.setActor(info);
        }else {
            Customer info = CustomerService.getInstance().findInfo(login_user.getId());
            login_user.setActor(info);
        }
        return login_user;
    }
}
